import Vue from 'vue';
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios)

const instance=axios.create({
    baseURL:'http://toutiao.itheima.net',
    timeout:10000
})

import {getToken,saveToken} from './token.js'
import {Toast} from 'vant'
import router from '@/router/index.js'
// 请求拦截器，处理token问题
instance.interceptors.request.use(config=>{
    if(getToken()){
        config.headers.Authorization=`Bearer ${getToken().token}`
    }
    return config
},err=>{
    return Promise.reject(err)
}
)
// // 响应拦截器处理刷新问题
instance.interceptors.response.use(response=>{
    return response
},async err=>{
    if(err.response&&err.response.status==401){
      if(getToken()){
        //   失效
try{
    let res=await axios({
        url:'http://toutiao.itheima.net/v1_0/authorizations',
        method:"put",
        headers:{
            'Authorization':`Bearer ${getToken().refresh_token}` 
        }
            })
       console.log(res);
       saveToken({
           token:res.data.data.token,
           refresh_token:getToken().refresh_token
       })
return instance(err.config)
}catch(err){
    Toast.success('请先登录')
    router.push('/login')
}
      }else{
        //   没有token，跳登录
        Toast.success('请先登录')
        router.push('/login')
      }  
    }else{
        // 不处理
    }
    return Promise.reject(err)
}
)
export default instance